package reqs

import (
	"github.com/gin-gonic/gin"
	"local.public/innerpkg/logger"
	"local.public/params"
	"local.public/utils"
	"strconv"
	"strings"
)

func GetHeaderValue(ctx *gin.Context, headerName string) string {

	for k, v := range ctx.Request.Header {
		if strings.ToLower(k) == strings.ToLower(headerName) {
			if len(v) > 0 {
				return v[0]
			}
		}
	}
	return ""

	//sFieldName := strings.ToUpper(headerName[0:1]) + headerName[1:]
	//vals, ok := ctx.Request.Header[sFieldName]
	//if ok {
	//	if len(vals) > 0 {
	//		return vals[0]
	//	}
	//}
	//return ""
}

func ExtractHeaderInfo(ctx *gin.Context) *params.HeaderParam {
	//logger.Debug("进入ExtractHeaderInfo")

	sToken := GetHeaderValue(ctx, "token")
	sEndpointType := GetHeaderValue(ctx, "end_type")

	//if sEndpointType == "admin" {
	//	return &params.HeaderParam{
	//		UserId:       0,
	//		UserName:     "admin",
	//		Token:        "",
	//		EndpointType: sEndpointType,
	//	}
	//}
	if sToken == "" {
		pHeaderParam := new(params.HeaderParam)
		return pHeaderParam
	}

	pTokenParam, err1 := (&utils.TokenOperator{}).ParseToken(sToken)
	if err1 != nil {
		logger.Debug(err1.Error())
		return nil
	}
	// 设置返回值
	pHeaderParam := new(params.HeaderParam)
	pHeaderParam.UserType = pTokenParam.UserType
	pHeaderParam.UserId, _ = strconv.Atoi(utils.IfEmpty(pTokenParam.UserId, "0"))
	pHeaderParam.UserName = pTokenParam.UserName
	pHeaderParam.RoleIds = pTokenParam.RoleIds
	pHeaderParam.ManageStoreIds = pTokenParam.ManageStoreIds
	pHeaderParam.Token = sToken
	pHeaderParam.EndType = sEndpointType
	return pHeaderParam
}
